package com.service.socket.ws.service;

import com.alibaba.fastjson.JSON;
import com.service.dao.enums.KlineTypeEnum;
import com.service.socket.common.entity.KlineStatisticVo;
import com.service.socket.common.entity.SendMessageVo;
import com.service.socket.common.enums.MsgSendType;
import com.service.socket.service.TradingKlineService;
import com.service.socket.support.TradingSpotCache;
import com.service.socket.ws.TradingSpotWS;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class KlineBroadcastService {
    @Autowired
    private TradingSpotWS spotWS;
    @Autowired
    private TradingSpotCache spotCache;
    @Autowired
    private TradingKlineService klineService;

    private Integer klineLimit = 80;

    public void broadcast(String symbol, Date klineDate){
        this.broadcastKline(symbol, klineDate);
        this.broadcastKlineStatistic(symbol, klineDate);
    }

    public void broadcastKline(String symbol, Date klineDate) {

        String currentStr = DateFormatUtils.format(klineDate, "yyyy-MM-dd HH:mm:ss");
        Arrays.stream(KlineTypeEnum.values()).forEach(type -> {
            log.info("symbol:{}, kline type:{}, current:{},limit:{}", symbol, type, currentStr, klineLimit);
            List<Object[]> result = klineService.list4ws(symbol, klineDate, type, klineLimit);
            String resultStr = JSON.toJSONString(result);
            spotCache.cacheKline(symbol, type.getValue(), resultStr);
            log.info("kline:{}", resultStr);
            //todo:send ws
            spotWS.broadcastThemeMsg(MsgSendType.kline,
                    SendMessageVo.builder().symbol(symbol)
                            .period(type.getValue())
                            .data(resultStr).build());
        });

    }

    public void broadcastKlineStatistic(String symbol, Date klineDate) {

        String currentStr = DateFormatUtils.format(klineDate, "yyyy-MM-dd HH:mm:ss");
        log.info("symbol:{}, current:{}", symbol, currentStr);

        KlineStatisticVo result = klineService.getKlineStatistic(symbol, klineDate);
        String resultStr = JSON.toJSONString(result);
        spotCache.cacheKlineStatistic(symbol, resultStr);
        log.info("symbol:{}, current:{}, statistic:{}", symbol, currentStr, resultStr);
        //todo:send ws
        spotWS.broadcastThemeMsg(MsgSendType.kline_statistics,
                SendMessageVo.builder().symbol(symbol)
                        .data(resultStr).build());

    }


}
